//
// Created by jsjxsy on 2022/8/22.
//
#include <fstream>
#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;
const char *file = "../data/planet.dat";
struct planet {
  char name[20];
  double popular;
  double g;
};
inline void eatline() {
  while (cin.get() != '\n')
    continue;
}

bool readWriteAppendBinaryFile() {
  cout<<fixed<<right;
  planet p1;
  ifstream fin;
  fin.open(file, ios_base::binary);
  if (fin.is_open()) {

    while (fin.read((char *) &p1, sizeof(p1))) {
      cout << setw(20) << p1.name << ":"
           << setprecision(0) << setw(12) << p1.popular
           << setprecision(2) << setw(6) << p1.g<<endl;
    }
    fin.close();
  } else {
    perror("file open fail:");
  }

  ofstream fout(file, ios_base::binary | ios_base::app);
  if (fout.is_open()) {
    string name;
    cout << "Enter planet names (enter a blank line to quit)" << endl;
    cin.get(p1.name, 20);
    while (p1.name[0] != '\0') {
      eatline();
      cout << "Enter planet population:";
      cin >> p1.popular;
      cout << "Enter planet g:";
      cin >> p1.g;
      eatline();
      fout.write((char *) &p1, sizeof(p1));
      cout << "Enter planet names (enter a blank line to quit)" << endl;
      cin.get(p1.name, 20);
    }
    fout.close();
  } else {
    perror("file open fail:");
    exit(EXIT_FAILURE);
  }
  fin.clear();
  fin.open(file,ios_base::binary);
  if (fin.is_open()) {
    while (fin.read((char *) &p1, sizeof(p1))) {
      cout << setw(20) << p1.name << ":"
           << setprecision(0) << setw(12) << p1.popular
           << setprecision(2) << setw(6) << p1.g<<endl;
    }
    fin.close();
  } else {
    perror("file open fail:");
  }
  cout << "Done!" << endl;
}

int main() {
  readWriteAppendBinaryFile();
  return 0;
}